const https = require('https');
const crypto = require('crypto');
const uuid = require('uuid');

const YOUDAO_URL = 'https://openapi.youdao.com/translate_html';
const APP_KEY = '296d4f5e3b1a946c';
const APP_SECRET = 'cl4cHX7KDcPZ3vTxMqY1UMn5bqJknUIA';

function encrypt(signStr) {
	return crypto.createHash('sha256').update(signStr, 'utf8').digest('hex');
}

function truncate(q) {
	if (!q) {
		return null;
	}
	const size = q.length;
	return size <= 20 ? q : q.substring(0, 10) + size + q.substring(size - 10, size);
}

function doRequest(data) {
	return new Promise((resolve, reject) => {
		const postData = new URLSearchParams(data).toString();
		const options = {
			hostname: 'openapi.youdao.com',
			path: '/translate_html',
			method: 'POST',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'Content-Length': Buffer.byteLength(postData),
			},
		};

		const req = https.request(options, (res) => {
			let data = '';

			res.on('data', (chunk) => {
				data += chunk;
			});

			res.on('end', () => {
				resolve({ headers: res.headers, body: data });
			});
		});

		req.on('error', (e) => {
			reject(e);
		});

		req.write(postData);
		req.end();
	});
}

async function connect(html: string) {
	const q = html;

	const data = {
		from: 'en',
		to: 'zh-CHS',
		signType: 'v3',
		curtime: Math.floor(Date.now() / 1000).toString(),
		salt: uuid.v1(),
		appKey: APP_KEY,
		q: q,
		sign: '',
	};

	const signStr = APP_KEY + truncate(q) + data.salt + data.curtime + APP_SECRET;
	data.sign = encrypt(signStr);

	try {
		const response: any = await doRequest(data);
		const contentType = response.headers['content-type'];

		if (contentType === 'audio/mp3') {
			const millis = Date.now();
			const filePath = `合成的音频存储路径${millis}.mp3`;
			require('fs').writeFileSync(filePath, response.body, 'binary');
		} else {
			console.log(response.body);
		}
	} catch (error) {
		console.error(error);
	}
}
export default connect;
